let get_dims img =
  ((Sdlvideo.surface_info img).Sdlvideo.w, (Sdlvideo.surface_info
					      img).Sdlvideo.h)

let sdl_init () =
  begin
    Sdl.init [`EVERYTHING];
    Sdlevent.enable_events Sdlevent.all_events_mask;
  end

let rec wait_key () =
  let e = Sdlevent.wait_event () in
    match e with
    Sdlevent.KEYDOWN _ -> ()
      | _ -> wait_key ()

let show img dst =
  let d = Sdlvideo.display_format img in
    Sdlvideo.blit_surface d dst ();
    Sdlvideo.flip dst

let level (r,g,b) = ((float_of_int(r)*.0.3) +. (float_of_int(g)*.0.59) +.
 (float_of_int(b)*.0.11)) /. 255.

let color2grey (r,g,b) =
  let a = int_of_float((level (r,g,b)) *. 255.) in
     (a,a,a)

let image2grey src dst =
  let (w,h) = get_dims src in
    for i = 0 to w-1 do
      for j = 0 to h-1 do
        Sdlvideo.put_pixel_color dst i j
	  (color2grey (Sdlvideo.get_pixel_color src i j))
      done
    done

let histogram src =
  let t = ref [||] in
    t := Array.make 256 0;
    let (w,h) = get_dims src in
      for i = 0 to w-1 do
        for j = 0 to h-1 do
          let a = int_of_float(level
				 (Sdlvideo.get_pixel_color src i j)*.255.) in
	    (!t).(a) <- (!t).(a) + 1;
        done
      done;
    t

let otsu src h =
  let ts = ref 0 and wb = ref 0 and wf = ref 0 in
  let sum = ref 0 and sumb = ref 0 and varmax = ref 0. in
    for t = 0 to 255 do
      sum := !sum + t * (!h).(t);
    done;
    for t = 0 to 255 do
    let (i,j) = get_dims src in
      wb := !wb + (!h).(t);
      wf := (i*j) - !wb;
      if (!wb != 0 && !wf != 0) then
	begin
	  sumb := !sumb + t * (!h).(t);
	  let mb = (float)(!sumb/(!wb))
	  and mf = (float)((!sum-(!sumb))/(!wf)) in
	  let varb = (float) !wb *.(float) !wf *.(mb-.mf) *.(mb-.mf) in
	  ts := if varb > !varmax then t else !ts;
	  varmax := if varb > !varmax then varb else !varmax;
	end
    done;
  !ts

let binarize src dst ts =
  let (w,h) = get_dims src in
    for i = 0 to w-1 do
      for j = 0 to h-1 do
        let a = int_of_float(level
			       (Sdlvideo.get_pixel_color src i j) *. 255.) in
          let b = if a < ts then 0 else 255 in
	    Sdlvideo.put_pixel_color dst i j (b,b,b);
      done
    done

let average l =
  let var = ref 0 in
  for i = 0 to 8 do
    var := !var + (!l).(i);
  done;
  (!var / 9)


let get (x, y, img) =
  let (g, _, _) = Sdlvideo.get_pixel_color img x y in
    g

let noise src dst =
  let (w,h)= get_dims src in
    for i = 1 to w-2 do
      for j = 1 to h-2 do
	let t = ref [||] in
	let a = ref 0 in
        t := Array.map get
 [|(i-1,j-1,src);(i-1,j,src);(i-1,j+1,src);
(i,j-1,src);(i,j,src);(i,j+1,src);
(i+1,j-1,src);(i+1,j,src);(i+1,j+1,src)|];
        a := average t;
        Sdlvideo.put_pixel_color dst i j (!a,!a,!a);
	done
      done
